/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.socialNet.dao.implementations;

import com.bionic.shsc.common.Utils;
import com.bionic.shsc.dao.interfaces.IUserDAO;
import com.bionic.socialNet.entities.LoginData;
import com.bionic.socialNet.entities.UserData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ann
 */
public class MySQLUser extends QueryExecutor implements IUserDAO {

   private final String INSERT_USER = "INSERT INTO `shsc`.`users`(`email`, `password_hash`,`create_time`,`user_type_id`)" +
" VALUES (%s,%s,current_date,2)"; // login,passHash
   
    private final String FIND_IS_ADMIN = "select * from users where login_email = '%s' and user_type = %d";

    // TEST
    @Override
    public UserData findUser(String userLogin) {
        String querySQL = "SELECT * FROM shsc.users where email = ? ";
        try {            
            PreparedStatement pstmt = query.getConnection().prepareStatement(querySQL);
            pstmt.setString(1, userLogin);
            ResultSet RS = pstmt.executeQuery();
            UserData user = new UserData();
            while (RS.next()) {
                user.setUserID(RS.getInt("user_id"));
                user.setEmail(RS.getString("login_email"));
                user.setUserTypeID(RS.getInt("user_type_id"));               
            }
            return user;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUser.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }
    
    @Override
    public int isLoginExecute(String login, String password) {
        String querySQL = "SELECT * FROM shsc.users where email = ? and password_hash =? ";     
        int count = 0;
        int userId = -1000;
        try {
              PreparedStatement pstmt = query.getConnection().prepareStatement(querySQL);
        pstmt.setString(1, login);
        String passHash = Utils.getHash(password);
        pstmt.setString(2, passHash); 
        ResultSet RS = pstmt.executeQuery(); 
            
            count = query.getRSRecordCount(RS);
            if (count > 0) {
                RS.first();
                userId = RS.getInt("user_id");
            }
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUser.class.getName()).log(Level.SEVERE, null, ex);
            return userId;            
        }
        return (userId);
    }
    
     @Override
    public boolean registerUser(UserData user) {     
        String queryText = String.format(INSERT_USER, user.getEmail(), user.getPass());
        boolean insertresult = query.executeInsertStatement(queryText);
        return insertresult;
    }

    // ДАЛЬШЕ ВСЕ ПОПЕРЕПИСЫВАТЬ
    
    // used for reset password
    @Override
    public boolean updateUser(UserData userData) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean isAdmin(int userID) {
        int i = 0;
        try {
            ResultSet rs = query.getRSForQuery(String.format(FIND_IS_ADMIN, userID, 100));
            i = query.getRSRecordCount(rs);
        } catch (Exception e) {
            return false;
        }
        return i > 0;
    }

  

    @Override
    public ArrayList<UserData> selectUsersList(String Criteria) {
        String sqlText = "select u.*, 1 as is_admin from users u where u.user_type = 100"
                + " union select u.*, 0 as is_admin from users u where u.user_type <> 100";
        ResultSet RS = query.getRSForQuery(sqlText);
        ArrayList<UserData> userDataList = new ArrayList<UserData>();
        try {
            while (RS.next()) {
                UserData user = new UserData();         
                user.setIsAdmin(RS.getInt("is_admin") == 1);
                user.setUserID(RS.getInt("user_id"));
                user.setEmail(RS.getString("LOGIN_EMAIL"));
                userDataList.add(user);
            }
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUser.class.getName()).log(Level.SEVERE, null,
                    ex);
        }
        return userDataList;
    }

    @Override
    public boolean isLoginAlreadyTaken(String login) {
        // TODO Auto-generated method stub
        ResultSet rs = query.getRSForQuery(String.format("", login));
        int count = 0;
        try {
            count = query.getRSRecordCount(rs);
        } catch (SQLException e) {
            return false;
        }
        return (count > 0);
    }

    
}
